﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.ExceptionManagement;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using AppName = Kiiro.Common.Utility.Constants.AppName;
using System.Drawing;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class EditSetup : BasePage
    {
        public Setup KiiroSetup { get; set; }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachments; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public string SuccessMessage
        {
            get { return ViewState [ "SuccessMessage" ] != null ? ( string ) ViewState [ "SuccessMessage" ] : default ( string ); }
            set { ViewState [ "SuccessMessage" ] = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Attachments.MaxLength = 1;
            Attachments.FileFormat = "jpg|png";

            if ( !CurrentUser.IsAdministrator )
            {
                Response.Redirect ( ServerRelativeUrl + "/_layouts/accessdenied.aspx?Source=" + ServerRelativeUrl );
            }
            else
            {
                KiiroSetup = SetupModel.GetMidoriSetup ( SiteCollectionId, ServerRelativeUrl ) ?? new Setup { EditType = EditType.Created };
        
                if ( !IsPostBack )
                {
                    lblInstanceCode.Text = SPHelpers.GetWebId ( SiteCollectionId, ServerRelativeUrl, true ).ToString ( );
                    lblServerCode.Text = SPHelpers.GetFarmId ( ).ToString ( );

                    PopulateSetup ( );
                    PopulateLicense ( );

                    litTitle.Text = AppName.Proper + " Settings";
                    if (!string.IsNullOrEmpty ( KiiroSetup.SiteName ))
                        litTitle.Text += " - " + KiiroSetup.SiteName;
                }
            }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            if ( ckbWPSandboxEnabled.Checked )
            {
                pnlWPSandboxNavText.Style.Add ( "display", "block" );
            }
            else
            {
                pnlWPSandboxEnabled.CssClass += " borderless";
                pnlWPSandboxNavText.Style.Add ( "display", "none" );
            }

            base.OnPreRender ( e );
        }

        protected void btnCancel_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( string.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.ProjectsActive ) );
        }

        protected void btnSave_Click ( object sender, EventArgs e )
        {
            Setup setup = new Setup ( );

            if ( KiiroSetup.EditType == EditType.Created )
            {
                setup.EditType = EditType.Created;
                setup.CreatedBy = CurrentUser;
                setup.CreatedDate = DateTime.Now;
            }
            else
            {
                setup.Id = KiiroSetup.Id;
                setup.EditType = EditType.Updated;
                setup.CreatedBy = KiiroSetup.CreatedBy;
                setup.CreatedDate = KiiroSetup.CreatedDate;
            }

            setup.AllowEmailReplies = chkAllowEmailReplies.Checked;
            setup.EmailFromAddress = txtSystemEmail.Text;
            setup.LicenseKey = txtLicenseKey.Text;

            List<Attachment> attachments = Attachments.GetAttachments ( );
            if ( attachments.Count > 0 )
            {
                Attachment attachment = attachments.Find ( x => x.Bytes != null && x.EditType != EditType.Deleted );
                if ( attachment != null )
                {
                    setup.LogoBytes = attachment.Bytes;
                    setup.LogoUrl = attachment.FileName;
                }
                else
                {
                    setup.LogoUrl = null;
                }
            }
            else
            {
                setup.LogoUrl = KiiroSetup.LogoUrl;
            }

            setup.POPInfo = txtPOPInfo.Text;
            setup.POPEmail = txtPopLogin.Text;
            setup.POPPassword = txtPopPassword.Text;
            setup.SendEmailUpdates = chkSendEmailUpdates.Checked;
            setup.SiteName = txtSiteName.Text;
            setup.SMTPInfo = txtSMTPInfo.Text;

            if (chkColorDefaults.Checked)
            {
                chkColorDefaults.Checked = false;
                SPHelpers.CustomSiteColorEdits(Color.Empty, Color.Empty, Color.Empty, Color.Empty, Color.Empty, Color.Empty, SiteCollectionId, ServerRelativeUrl);
            }
            else
            {
                Color portalHeadline = SPHelpers.HexToColor(txtPortalHeadline.Text);
                Color portalMenu = SPHelpers.HexToColor(txtPortalMenu.Text);
                Color projectHeadline = SPHelpers.HexToColor(txtProjectHeadline.Text);
                Color projectMenu = SPHelpers.HexToColor(txtProjectMenu.Text);
                Color links = SPHelpers.HexToColor(txtLinks.Text);
                Color titles = SPHelpers.HexToColor(txtTitleColor.Text);
                SPHelpers.CustomSiteColorEdits(portalHeadline, portalMenu, projectHeadline, projectMenu, links, titles, SiteCollectionId, ServerRelativeUrl);
            }

            double hoursPerDay = 8.0;
            double.TryParse ( txtHoursPerDay.Text, out hoursPerDay );
            setup.HoursPerDay = hoursPerDay;

            setup.ModifiedBy = CurrentUser;
            setup.ModifiedDate = DateTime.Now;

            setup.IsWPSandboxActivated = ckbWPSandboxEnabled.Checked;
            setup.WPSandboxNavText = setup.IsWPSandboxActivated ? txtWPSandboxNavText.Text : default ( string );

            SetupModel.Save ( setup, SiteCollectionId, ServerRelativeUrl );

            ValidateSave ( setup );
        }

        private void PopulateSetup ( )
        {
            txtSiteName.Text = KiiroSetup.SiteName ?? SPHelpers.GetWebTitle ( SiteCollectionId, ServerRelativeUrl );

            string logoUrl = SetupModel.GetLogo ( SiteCollectionId, ServerRelativeUrl );
            if ( !string.IsNullOrEmpty ( logoUrl ) )
            {
                Attachment attachment = new Attachment ( );
                attachment.FileName = logoUrl;
                attachment.ServerRelativeUrl = logoUrl;
                Attachments.SetAttachments ( new List<Attachment> ( ) { attachment } );
            }

            if ( string.IsNullOrEmpty ( KiiroSetup.EmailFromAddress ) || string.IsNullOrEmpty ( KiiroSetup.SMTPInfo ) )
            {
                string spEmailAddress = default ( string );
                string spEmailServer = default ( string );

                SetupModel.GetSharePointOutgoingEmailSettings ( SiteCollectionId, ServerRelativeUrl, out spEmailAddress, out spEmailServer );

                txtSystemEmail.Text = spEmailAddress ?? string.Empty;
                txtSMTPInfo.Text = spEmailServer ?? string.Empty;

                chkSendEmailUpdates.Checked = KiiroSetup.SendEmailUpdates && !string.IsNullOrEmpty ( txtSystemEmail.Text ) && !string.IsNullOrEmpty ( txtSMTPInfo.Text );
            }
            else
            {
                txtSystemEmail.Text = KiiroSetup.EmailFromAddress;
                txtSMTPInfo.Text = KiiroSetup.SMTPInfo;

                chkSendEmailUpdates.Checked = KiiroSetup.SendEmailUpdates && SetupModel.GetSMTPServerExists ( SiteCollectionId, ServerRelativeUrl );
            }

            chkAllowEmailReplies.Checked = KiiroSetup.AllowEmailReplies;
            txtPOPInfo.Text = KiiroSetup.POPInfo ?? string.Empty;
            txtPopLogin.Text = KiiroSetup.POPEmail ?? string.Empty;
            txtPopPassword.Text = KiiroSetup.POPPassword ?? string.Empty;
            txtHoursPerDay.Text = KiiroSetup.HoursPerDay.ToString ( "F1" ) ?? "8.0";

            ckbWPSandboxEnabled.Checked = KiiroSetup.IsWPSandboxActivated;
            txtWPSandboxNavText.Text = KiiroSetup.WPSandboxNavText;
        }

        private void PopulateLicense ( )
        {
            txtLicenseKey.Text = KiiroSetup.LicenseKey;

            LicensingManifest allKeysManifest = LicensingModel.GetAllKeysManifest ( KiiroSetup, SiteCollectionId, ServerRelativeUrl );
            if ( allKeysManifest != null )
            {
                rblLicenseType.SelectedIndex = allKeysManifest.IsServerLicense ? 1 : 0;

                string openProjectsCount = LicensingModel.GetOpenProjectsCount ( SiteCollectionId, ServerRelativeUrl ).ToString ( );
                string openProjectsLimit = Double.IsInfinity ( allKeysManifest.OpenProjectsLimit ) ? "Unlimited" : allKeysManifest.OpenProjectsLimit.ToString ( );

                string activeUsersCount = LicensingModel.GetActiveUsersCount ( SiteCollectionId, ServerRelativeUrl ).ToString ( );
                string activeUsersLimit = Double.IsInfinity ( allKeysManifest.ActiveUsersLimit ) ? "Unlimited" : allKeysManifest.ActiveUsersLimit.ToString ( );

                lblProjectSiteLimit.Text = String.Format ( "Using {0} of {1}", openProjectsCount, openProjectsLimit );
                lblUserLimit.Text = String.Format ( "Using {0} of {1}", activeUsersCount, activeUsersLimit );
            }
        }

        private void ValidateSave ( Setup setup )
        {
            if ( setup.IsValid ( ) )
            {
                // force a reset of the Permission bits so that if the key has changed the error message control will truly be cleared of error messages
                //			this will prevent the "cached" error messages from appearing
                PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( this, this.CurrentUser, this.SiteCollectionId, this.ServerRelativeUrl );

                KiiroSetup = setup;
                KiiroMaster.V2ErrorsList.ErrorMessages.Clear ( );

                if ( this.LicenseKeyIsValid )
                {
                    KiiroMaster.V2ErrorsList.ErrorMessages.Add ( "Kiiro settings updated successfully." );
                    KiiroMaster.V2ErrorsList.OperationStatus = OperationStatus.Success;
                }
                PopulateSetup ( );
                PopulateLicense ( );
            }
            else
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Clear ( );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( "There are some submission errors with the form. Errors will be shown in red below the fields." );
                KiiroMaster.V2ErrorsList.OperationStatus = OperationStatus.Failure;
            }

            lblAllowEmailRepliesMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.AllowEmailRepliesMessage );
            lblLicenseKeyMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.LicenseKeyMessage );
            lblPOPInfoMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.POPInfoMessage );
            lblSendEmailUpdatesMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.SendEmailUpdatesMessage );
            lblSiteNameMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.SiteNameMessage );
            lblSMTPInfoMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.SMTPInfoMessage );
            lblPopPasswordInfoMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.POPPasswordMessage );
            lblPopLoginInfoMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.POPEmailMessage );
            lblSystemEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.EmailFromAddressMessage );
            lblHoursPerDayMessage.Text = FormattingHelpers.GetErrorMessageText ( setup.HoursPerDayMessage );
            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText ( setup.LogoBytesMessage );
            lblWPSandboxEnabled.Text = FormattingHelpers.GetErrorMessageText ( setup.IsWPSandboxActivatedMessage );
            lblWPSandboxNavText.Text = FormattingHelpers.GetErrorMessageText ( setup.WPSandboxNavTextMessage );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.PortalPages/Setup/EditSetup.aspx.cs $
 * 
 * 30    2/08/10 2:28p Camerons
 * 
 * 29    1/12/10 3:02p Camerons
 * 
 * 28    1/06/10 12:39p Camerons
 * 
 * 27    4/01/10 12:03p Adamw
 * 
 * 26    12/18/09 3:26p Camerons
 * 
 * 25    12/16/09 4:05p Stefanf
 * 
 * 24    26/11/09 10:02a Camerons
 * 
 * 23    7/11/09 1:14p Camerons
 * 
 * 22    16/10/09 5:40p Shafia
 * Set Attachments Properties MaxLength, and FileFormat to allow one file
 * and .jpg or .png files only.
 * 
 * 21    8/10/09 6:41p Camerons
 * Updates for Server License
 * 
 * 20    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 19    28/09/09 3:38p Camerons
 * 
 * 18    23/09/09 3:21p Camerons
 * 
 * 17    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/